package cn.xingzhe.monster.user.infrastructure.service;

import cn.xingzhe.monster.user.domain.enums.CaptchaTypeEnum;
import cn.xingzhe.monster.user.domain.service.EmailSender;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.regex.Pattern;

/**
 * 邮件发送服务实现
 * 基于Spring Mail实现
 *
 * @author System
 * @version 1.0.0
 * @since 2024-01-01
 */
@Component
public class SpringEmailSender implements EmailSender {

    private static final Pattern EMAIL_PATTERN = Pattern.compile("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$");

    private final JavaMailSender mailSender;

    @Value("${spring.mail.username:}")
    private String fromEmail;

    public SpringEmailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    @Override
    public void sendEmail(String email, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromEmail);
        message.setTo(email);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }

    @Override
    public void sendRegisterCaptcha(String recipient, String code) {
        String subject = "注册验证码";
        String content = String.format("您的注册验证码是：%s，有效期为5分钟，请勿泄露给他人。", code);
        sendEmail(recipient, subject, content);
    }

    @Override
    public void sendLoginCaptcha(String recipient, String code) {
        String subject = "登录验证码";
        String content = String.format("您的登录验证码是：%s，有效期为5分钟，请勿泄露给他人。", code);
        sendEmail(recipient, subject, content);
    }

    @Override
    public boolean supports(String recipient) {
        return EMAIL_PATTERN.matcher(recipient).matches();
    }
}

